package com.shelpe.services.lexicon.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;

import com.shelpe.services.lexicon.entity.AdgroupRecord;
import com.shelpe.services.lexicon.entity.AdgroupRecord.Action;
import com.shelpe.services.lexicon.entity.KeywordSource;
import com.shelpe.services.lexicon.po.Adgroup;
import com.shelpe.services.lexicon.po.Creative;
import com.shelpe.services.lexicon.repository.jpa.AdgroupRepository;
import com.shelpe.services.lexicon.repository.jpa.CreativeRepository;
import com.shelpe.services.lexicon.repository.mongo.AdgroupRecordRepository;

@Service
public class AdgroupRecordService {

	@Autowired
	private AdgroupRepository adgroupRepository;
	@Autowired
	private CreativeRepository creativeRepository;
	@Autowired
	private AdgroupRecordRepository adgroupRecordRepository;
	
	public AdgroupRecord createFromAdgroup(long adgroupID){
		AdgroupRecord record = null;
		
		Adgroup adgroup = this.adgroupRepository.findOne(adgroupID);
		if(adgroup != null){
			record = new AdgroupRecord();
			record.setAdgroupID(adgroupID);
			record.setCampaignID(adgroup.getCampaignID());
			record.setItemID(adgroup.getProductID());
			record.setNickName(adgroup.getNick());
			record.setTanentID(adgroup.getUserID());
			record.setPostTime(new Date());
			
			String cateIDstr = adgroup.getCategoryIDs();
			if(cateIDstr != null){
				String[] cateIDs = cateIDstr.split("\\s");
				int[] ids = null;
				for(String cateID: cateIDs){
					if(NumberUtils.isNumber(cateID)){
						ids = ArrayUtils.add(ids, NumberUtils.toInt(cateID));
					}
				}
				if(ids != null && ids.length > 0){
					record.setCategoryIDs(ids);
				}
			}
			List<AdgroupRecord> existings = this.adgroupRecordRepository.findByAdgroupID(adgroupID);
			if(existings != null && existings.size() > 0){
				record.setAction(Action.update);
			}else{
				record.setAction(Action.create);
			}
			
			KeywordSource source = new KeywordSource();
			source.setItemName(adgroup.getProductName());
			List<Creative> creatives = this.creativeRepository.findByAdgroupID(adgroupID);
			if(creatives != null){
				for(Creative creative:creatives){
					source.addCreativeName(creative.getTitle());
				}
			}
			record.setSource(source);
			record.setCreateTime(new Date());
			record.setLastModifiedTime(new Date());
			this.adgroupRecordRepository.save(record);
		}else{
			throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "adgroup_not_found");
		}
		return record;
	}
}
